package com.work.service.impl;

import com.work.dao.AddressDao;
import com.work.dao.CartDao;
import com.work.pojo.Address;
import com.work.pojo.Cart;
import com.work.pojo.Goods;
import com.work.service.CartService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.List;

@Service
@Transactional(rollbackFor = Exception.class, readOnly = true, propagation = Propagation.SUPPORTS)
public class CartServiceImpl implements CartService {
    @Autowired
    private CartDao cartDao;
    @Autowired
    private AddressDao addressDao;

    @Override
    public List<Cart> getCart(Integer uid) {
        System.out.println( uid );
        return cartDao.getCart( uid );
    }

    @Override
    public void addCart(Cart cart) {
        Integer id = cart.getId();
        Integer pid = cart.getPid();
        Goods goods = cartDao.selectGoods( pid );
        Cart havecart = cartDao.selectone( id, pid );
        if (havecart != null) {
            Integer num = havecart.getNum();
            num += cart.getNum();
            havecart.setNum( num );
            BigDecimal price = goods.getPrice();
            BigDecimal multiply = price.multiply( BigDecimal.valueOf( num ) );
            havecart.setMoney( multiply );
            cartDao.upDate( havecart );
        } else {
            BigDecimal price = goods.getPrice();
            cart.setMoney( price.multiply( BigDecimal.valueOf( cart.getNum() ) ) );
            cartDao.addCart( cart );
        }
    }


    @Override
    public void addCartAjax(Integer uid, int number, int pid) {

        if (number == 0) {
            cartDao.deleteCart( uid, String.valueOf( pid ) );
        }
        Goods goods = cartDao.selectGoods( pid );
        BigDecimal price = goods.getPrice();
        Cart havecart = cartDao.selectone( uid, Integer.valueOf( pid ) );
        if (havecart != null) {
            havecart.setNum( havecart.getNum() + number );
            havecart.setMoney( price.multiply( BigDecimal.valueOf( havecart.getNum() ) ) );
            cartDao.upDate( havecart );
        } else {
            if (number > 0) {
                Cart cart1 = new Cart( uid, pid, number, price.multiply( BigDecimal.valueOf( number ) ) );
                cartDao.insertCart( cart1 );
            }
        }
    }

    @Override
    public void clearCartAjax(Integer uid) {
        cartDao.clearCartAjax( uid );
    }

    @Override
    public List<Address> getAddress(Integer uid) {
        return addressDao.getAddress( uid );
    }
}
